//
//  HomeViewController.m
//  CarOfHome2
//
//  Created by dlios on 15/9/23.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "HomeViewController.h"
#import "NetworkHandle.h"

#import "STYHomeSliderModel.h"
#import "HomeModel.h"
#import "STYHomeBtnModel.h"

#import "STYHomeCell.h"
#import "HomeMenuView.h"
#import "HomeHeaderView.h"
#import "HomeAddMenuView.h"
#import "WebViewController.h"


#import "SearchNews.h"

#import "ConnectedToNetwork.h"

@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,HomeMenuViewDelegate>


@property (nonatomic, strong) NSMutableArray *btnArray;
@property (nonatomic, strong) NSMutableArray *oldArray;
@property (nonatomic, strong) NSMutableArray *homeCellArray;
@property (nonatomic, strong) NSMutableArray *homeSliderArray;
@property (nonatomic, strong) HomeMenuView *menuView;
@property (nonatomic, strong) HomeHeaderView *headerView;
@property (nonatomic, copy) NSMutableString *url;
@property (nonatomic, assign) NSInteger page;
/** 当前button */
@property (nonatomic, strong) STYHomeBtnModel *currentBtn;
/** 当前位置 */
@property (nonatomic, assign) NSInteger currentIndex;
/** 加载 */
@property (nonatomic, strong) MBProgressHUD *HUD;
/* 搜索 */
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIButton *rightButton;


@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated
{
    AppDelegate *dele = [[UIApplication sharedApplication]delegate];
    if (dele.isNight == 1) {
       // self.view.backgroundColor = [UIColor blackColor];
        self.tableView.backgroundColor = [UIColor blackColor];
        [self.tableView reloadData];
    }
    else{
       // self.view.backgroundColor = [UIColor whiteColor];
        self.tableView.backgroundColor = [UIColor whiteColor];
        [self.tableView reloadData];
    }
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
    
    if (self.homeCellArray.count == 0)
    {
        //马上进入刷新状态
        [self.tableView.header beginRefreshing];
        
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    self.title = @"首页";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"list"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"BBJJ"]];
    
//    self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:0.877 green:0.887 blue:0.965 alpha:1.000];
    
    /* 搜索按钮 */
    UIView *rightBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SAWindth * 60, SAHeight * 30)];
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.frame = CGRectMake(SAWindth * 0, 5, SAHeight * 50, 25);
    [self.rightButton setTitle:@" 🔍 " forState:UIControlStateNormal];
    [self.rightButton addTarget:self action:@selector(souSuo:) forControlEvents:UIControlEventTouchDown];
    [rightBarView addSubview:self.rightButton];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:rightBarView];
    self.navigationItem.rightBarButtonItem = right;

    self.homeCellArray = [NSMutableArray array];
    
    [self ViewSubviews];
    [self setBtnArrayWithArray];
    [self upLoading];
    
}

/* 搜索 */
- (void)souSuo:(UIButton *)button
{
    NSLog(@"搜索");
    SearchNews *search = [[SearchNews alloc] init];
    search.searchURLString = @"http://mi.xcar.com.cn/interface/xcarapp/searchNews.php";
    search.searchType = 1;
    [self.navigationController pushViewController:search animated:YES];
}

#pragma mark - 
- (void)Closed
{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"加载中..";
    [self.HUD show:YES];
    self.view.userInteractionEnabled = NO;

}
- (void)Opend
{
    [self.HUD hide:YES afterDelay:2];
    self.view.userInteractionEnabled = YES;

}


#pragma mark -

- (void)setBtnArrayWithArray
{
    self.btnArray = [NSMutableArray array];
    self.oldArray = [NSMutableArray array];
    self.currentIndex = 0;
    
    
    STYHomeBtnModel *model1 = [[STYHomeBtnModel alloc] init];
    model1.btnName = @"最新";
    model1.btnIndex = 1;
    model1.btnNameEngligh = @"First";
    [self.btnArray addObject:model1];
    
    STYHomeBtnModel *model2 = [[STYHomeBtnModel alloc] init];
    model2.btnName = @"新闻";
    model2.btnIndex = 2;
    model2.btnNameEngligh = @"news";
    [self.btnArray addObject:model2];
    
    STYHomeBtnModel *model3 = [[STYHomeBtnModel alloc] init];
    model3.btnName = @"导购";
    model3.btnIndex = 4;
    model3.btnNameEngligh =@"buy";
    [self.btnArray addObject:model3];
    
    STYHomeBtnModel *model4 = [[STYHomeBtnModel alloc] init];
    model4.btnName = @"评测";
    model4.btnIndex = 3;
    model3.btnNameEngligh =@"ping";
    [self.btnArray addObject:model4];
    
    STYHomeBtnModel *model5 = [[STYHomeBtnModel alloc] init];
    model5.btnName = @"新车谍照";
    model5.btnIndex = 8;
    model5.btnNameEngligh =@"newCar";
    [self.btnArray addObject:model5];
    
    self.currentBtn = model1;
    
    [self dataHandle:model1];
    
    self.menuView.butArr = self.btnArray;
    self.menuView.index = self.currentIndex;
    
    
    NSArray *tempArr = @[
                     @{@"btnName": @"新车上市",@"btnIndex": @"3"},
                     @{@"btnName": @"奇闻车事",@"btnIndex": @"1540"},
                     @{@"btnName": @"油价变动",@"btnIndex": @"1"},
                     @{@"btnName": @"多车对比",@"btnIndex": @"20"},
                     @{@"btnName": @"改装升级",@"btnIndex": @"83757"},
                     @{@"btnName": @"车辆召回",@"btnIndex": @"2"},
                     @{@"btnName": @"新技术",@"btnIndex": @"4"},
                     @{@"btnName": @"能源汽车",@"btnIndex": @"6"},
                     @{@"btnName": @"概念车",@"btnIndex": @"18534"},
                     @{@"btnName": @"激情购车",@"btnIndex": @"33"},
                     @{@"btnName": @"汽车音响",@"btnIndex": @"985"},
                     @{@"btnName": @"SUV对比",@"btnIndex": @"76392"},
                     @{@"btnName": @"对比选车",@"btnIndex": @"28"},
                     @{@"btnName": @"购车技巧",@"btnIndex": @"76395"}];
    
    for (NSDictionary *dic in tempArr) {
        STYHomeBtnModel *model = [[STYHomeBtnModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.oldArray addObject:model];
        NSLog(@"%@",model.btnName);
        
    }
    
    
}
//页面布局
- (void)ViewSubviews
{
    self.menuView = [[HomeMenuView alloc] initWithFrame:CGRectMake(0, 0 * SAHeight, 375 * SAWindth, 30 * SAHeight)];
    self.menuView.delegate = self;
    [self.view addSubview:self.menuView];
    
    [self.menuView.addMenu addTarget:self action:@selector(addMenu:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30 * SAHeight, 375 * SAHeight, self.view.frame.size.height - 74 * SAHeight) style:UITableViewStylePlain];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"STYHomeCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"reuse"];
    
    self.headerView = [[HomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, 375 * SAWindth, 200 * SAHeight)];
    
   
}

//添加按钮
- (void)addMenu:(UIButton *)button
{
    
    static HomeAddMenuView *addMenuView = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        addMenuView = [[HomeAddMenuView alloc] initWithFrame:CGRectMake(0, - 533 * SAHeight, 375 * SAWindth, 533 * SAHeight)];
        [self.view addSubview:addMenuView];

    });
    
    button.selected = !button.selected;
    if (button.selected) {
        
    
        [UIView animateWithDuration:0.5 animations:^{
            addMenuView.frame = CGRectMake(0, 30 * SAHeight, 375 * SAWindth, 533 * SAHeight);
            addMenuView.menuArr = self.btnArray;
            addMenuView.oldMenuArr = self.oldArray;
            self.menuView.scrollView.userInteractionEnabled = NO;
        }];
        
        
    }
    else
    {
        [UIView animateWithDuration:0.5 animations:^{
            addMenuView.frame = CGRectMake(0, -533 * SAHeight, 375 * SAWindth, 533 * SAHeight);
            
            self.btnArray = addMenuView.menuArr;
            self.oldArray = addMenuView.oldMenuArr;
            
            self.menuView.butArr = self.btnArray;
            
            NSInteger count = self.btnArray.count;
            NSInteger i = 0;
            for (STYHomeBtnModel *model in self.btnArray) {
                if ([model.btnName isEqualToString:self.currentBtn.btnName]) {
                    self.currentIndex = i;

                }
                else
                {
                    i++;
                }
            }
            if (i == count) {
                self.menuView.index = 0;
                STYHomeBtnModel *model = [[STYHomeBtnModel alloc] init];
                model.btnName = @"最新";
                model.btnIndex = 1;
                [self dataHandle:model];
                [self.tableView.header beginRefreshing];
            }
            else
            {
                self.menuView.index = self.currentIndex;
            }
            
            
            self.menuView.scrollView.userInteractionEnabled = YES;
        }];
        
        
    }
    
}


//数据加载
- (void)dataHandle:(STYHomeBtnModel *)model
{
    NSMutableString *appendPath = [NSMutableString stringWithFormat:@"home/%@.da",self.currentBtn.btnNameEngligh];
    
    
    if (![ConnectedToNetwork connectedToNetwork]) {
        
        self.homeCellArray = [NSMutableArray array];
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:appendPath];
        
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        
        if (array.count != 0) {
            for (NSDictionary *dic in array) {
                HomeModel *mod = [HomeModel setHomeModelWithDictionary:dic];
                [self.homeCellArray addObject:mod];
            }
            
            [self.tableView reloadData];
            [self Opend];
        }
        else
        {
            
        }

    }
    else
    {
    [self Closed];
    self.page = 10 ;
    NSMutableString *homeUrl;
    if ([model.btnName isEqualToString:@"最新"] || [model.btnName isEqualToString:@"新闻"] || [model.btnName isEqualToString:@"导购"] || [model.btnName isEqualToString:@"评测"]) {
        
       homeUrl = [NSMutableString stringWithFormat:@"%s%s",Home,Home1];
        
    }
    else
    {
        
    homeUrl = [NSMutableString stringWithFormat:@"%s%s",HomeMi,Home1];
    
    
    }
    
    [homeUrl appendFormat:@"%ld",model.btnIndex];
    
    self.url = [NSMutableString stringWithString:homeUrl];
    
    NSInteger i = 0;
    [homeUrl appendFormat:@"%s%ld",HomePage,i];
    
    
    NSMutableArray *arr = [NSMutableArray array];
    
    //刷新数据
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
   
        
    if (model.btnIndex == 1) {
        
        [NetworkHandle GETWithURL:homeUrl complication:^(id result) {
            /**
             *  轮播图数组加载数据
             */
            NSArray *tempArr = result[@"focusList"][@"focusImgs"];
        
            self.homeSliderArray = [NSMutableArray array];
            for (NSDictionary *dic in tempArr) {
                STYHomeSliderModel *model = [STYHomeSliderModel setStyHomeSliderModelWithDictionary:dic];
                [self.homeSliderArray addObject:model];
            }
            
            /**
             *  cell数组加载数据
             */
            NSArray *tempArr1 = [result objectForKey:@"newsList"];
            
            NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"home"];
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            
            [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            
            NSString *component = [NSString stringWithFormat:@"%@.da",self.currentBtn.btnNameEngligh];
            
            NSString *disPath = [path stringByAppendingPathComponent:component];
            
            [tempArr1 writeToFile:disPath atomically:YES];
            
            for (NSDictionary *dic in tempArr1) {
                HomeModel *model = [HomeModel setHomeModelWithDictionary:dic];
                [arr addObject:model];
            }
            self.homeCellArray = arr;
            
            self.tableView.tableHeaderView = self.headerView;
            self.headerView.sliderArr = self.homeSliderArray;
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
            
            [self Opend];
            
            }];

        
        
    }
    else
    {
        self.homeCellArray = [NSMutableArray array];
        
        [NetworkHandle GETWithURL:homeUrl complication:^(id result) {
            /**
             *  cell数组加载数据
             */
            NSArray *tempArr = [result objectForKey:@"newsList"];
            
            
            
            for (NSDictionary *dic in tempArr) {
                HomeModel *model = [HomeModel setHomeModelWithDictionary:dic];
                [arr addObject:model];
            }
            self.homeCellArray = arr;
            
            self.tableView.tableHeaderView = nil;
            
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
            
            [self Opend];
            
        }];
    }
    }];
    
    
    }
  
}

- (void)upLoading
{
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        [self Closed];
        NSMutableString *tempUrl = [NSMutableString stringWithFormat:@"%@",self.url];
        
        [tempUrl appendFormat:@"%s",HomePage];
        
        [tempUrl appendFormat:@"%ld",self.page];
                                     
        self.page += 10;
        
        [NetworkHandle GETWithURL:tempUrl complication:^(id result) {
            /**
             *  cell数组加载数据
             */
            NSArray *tempArr = [result objectForKey:@"newsList"];
            for (NSDictionary *dic in tempArr) {
                HomeModel *model = [HomeModel setHomeModelWithDictionary:dic];
                [self.homeCellArray addObject:model];
            }
            
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
            
            [self Opend];
            
            if (tempArr.count == 0) {
                /* 数据就不在加载 */
                [self.tableView.footer noticeNoMoreData];
            }
            
        }];
        
    }];
}

#pragma mark - dataSourse协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.homeCellArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    STYHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    
    HomeModel *model = self.homeCellArray[indexPath.row];
    
    cell.model = model;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


#pragma mark - delegate协议

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    HomeModel *model = self.homeCellArray[indexPath.row];
    WebViewController *webView = [[WebViewController alloc] init];
    webView.viewTitle = model.newsTitle;
    webView.viewUrl = model.newsLink;
    webView.viewType = @"首页";
    [self.navigationController pushViewController:webView animated:YES];
    
    
}


#pragma mark - homeMenu协议

- (void)passValueWithBtnModel:(STYHomeBtnModel *)model
{
    
    NSLog(@"%@",model.btnName);
    [self dataHandle:model];
    [self.tableView.header beginRefreshing];
    self.currentBtn = model;
    self.page = 10;
    
}

#pragma mark - Memory
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
